﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace RssReader.Core.UI
{
	public abstract class BaseControl : WebControl, INamingContainer
	{
		#region Private Properties
		private string _skinPath;
		private BasePage _currentPage;
		#endregion

		#region Public Properties
		protected string SkinPath
		{
			get
			{
				return _skinPath;
			}
			set
			{
				if (String.IsNullOrEmpty(value))
				{
					throw new ArgumentException("template path can not be empty");
				}
				_skinPath = value;
			}
		}

		public BasePage CurrentPage
		{
			get
			{
				return _currentPage;
			}
		}
		#endregion

		#region Constructors

		#endregion

		#region Private Methods
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			_currentPage = this.Page as BasePage;
		}
		protected override void CreateChildControls()
		{
			base.CreateChildControls();
			//set default skin path if its empty.
			if (String.IsNullOrEmpty(_skinPath))
			{
				_skinPath = "Resources.ControlTemplates." + this.GetType().Name + ".ascx";
			}
			this.LoadSkin();
			this.AttachChildControls();
		}

		public override Control FindControl(string id)
		{
			Control control = base.FindControl(id);
			if (control == null && this.Controls.Count == 1)
			{
				control = this.Controls[0].FindControl(id);
			}
			return control;
		}

		protected void LoadSkin()
		{
			this.Controls.Clear();
			
			string assem = this.GetType().Assembly.GetName().Name;
			string skinPath = "~/AssemblyResources/" + assem + "/" + assem + "." + _skinPath;
			Control control = this.Page.LoadControl(skinPath);
			this.Controls.Add(control);
		}

		protected abstract void AttachChildControls();
		#endregion

		#region Public Methods
		public void ThrowError(string errorMessage)
		{
			_currentPage.ThrowError(errorMessage);
		}
		#endregion
	}
}
